 //
//  JrdChangeAccountViewController.m
//  iMandarin
//
//  Created by longcheng on 16/7/4.
//  Copyright © 2016年 Singro. All rights reserved.
//

#import "JrdChangeAccountViewController.h"
#import "JrdCommon.h"
#import "UIColor+JRDNote.h"
#import "JrdLoginViewController.h"
#import "JrdDatamanager.h"
#import "JrdChangeAccountCellTableViewCell.h"
#import "JrdChangePasswordViewController.h"
#import "JrdChangeEmailViewController.h"
#import "JrdChangePhoneViewController.h"
#import "CKHttpCommunicate.h"
#define JRD_CHANGE_INFO_SECTION 0
#define JRD_CHANGE_LOGOUT_SECTION  1

#define JRD_CHANGE_PHOTO 0
#define JRD_CHANGE_PWD 1
#define JRD_CHANGE_EMAIL 2
#define JRD_CHANGE_PHONE 3
#define JRD_LOGOUT  4

#define JRD_CHANGE_SECTION 5
@interface JrdChangeAccountViewController ()<UITableViewDataSource, UITableViewDelegate, UIViewControllerPreviewingDelegate, UIAlertViewDelegate>{
    int section_number;
    Boolean is_need_uploadImage;
}
@property (nonatomic, strong) SCBarButtonItem *leftBarItem;
@property (nonatomic, strong) SCBarButtonItem *rightBarItem;
@property (nonatomic, strong) NSString* imagePath;

@end

@implementation JrdChangeAccountViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    self.sc_navigationItem.leftBarButtonItem = self.leftBarItem;
    self.sc_navigationItem.rightBarButtonItem = self.rightBarItem;
    is_need_uploadImage = false;
    //image picker
    //获取Documents文件夹目录
    NSArray *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentPath = [path objectAtIndex:0];
    //指定新建文件夹路径
    NSString *imageDocPath = [documentPath stringByAppendingPathComponent:@"ImageFile"];
    //创建ImageFile文件夹
    [[NSFileManager defaultManager] createDirectoryAtPath:imageDocPath withIntermediateDirectories:YES attributes:nil error:nil];
    //保存图片的路径
    self.imagePath = [imageDocPath stringByAppendingPathComponent:@"image.png"];

    NSDictionary *parameter_ = @{
                                 @"userid":[JrdDatamanager manager].user.userId
                                 };

    [CKHttpCommunicate createRequest:HTTP_GET_USER_INFO WithParam:parameter_ withMethod:GET success:^(id result) {
        if(result){
            [JrdDatamanager manager].user.userEamil = [result[0] valueForKey:@"email"];
            [JrdDatamanager manager].user.phoneNumber = [result[0] valueForKey:@"phone"];
            
            [[JrdDatamanager manager] setUserEmail:[result[0] valueForKey:@"email"]];
            [[JrdDatamanager manager] setUserPhone:[result[0] valueForKey:@"phone"]];
            [self.tableView reloadData];
        }
    }failure:^(NSError *erro) {
    } showHUD:nil];

    NSDictionary *parameter_1 = @{@"userid":[JrdDatamanager manager].user.userId};
    
    [CKHttpCommunicate createRequest:HTTP_GET_IMAGE WithParam:parameter_1 withMethod:GET success:^(id result) {
        if(result){
            [self loadImageAndSave:result];
        }
    }failure:^(NSError *erro) {
        NSLog(@"zlwu add ");
    } showHUD:self.view];

    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(reloadAccountImage)
                                                 name:kPickImageNotification
                                               object:nil];

}

- (void)viewDidAppear:(BOOL)animated{
    self.sc_navigationItem.title = NSLocalizedString(@"v2_Account",nil);//@"我们学习";

}

- (void)reloadData{
    [self.tableView reloadData];
}

- (void)reloadAccountImage{
    dispatch_async(dispatch_get_main_queue(), ^{
        UIImage *image=[UIImage imageWithContentsOfFile:self.imagePath];
        UIImageView* imageView = (UIImageView*)[self.view viewWithTag:100];
        //根据图片路径载入图片
        if (image == nil) {
            imageView.image= [UIImage imageNamed:@"ico_username"];
        }else {
            //显示保存过的
            imageView.image  = image;
        }
    });
}

- (void)viewWillAppear:(BOOL)animated{
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(reloadData)
                                                 name:kReloadUserNotification
                                               object:nil];

}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


- (void)loadView {
    [super loadView];
    [self configureTableView];
    [self configureNavibarItems];
    
}

- (void)configureNavibarItems {
    self.leftBarItem = [[SCBarButtonItem alloc] initWithTitle:NSLocalizedString(@"jrd_cancel", nil) style:SCBarButtonItemStylePlain handler:^(id sender) {
        [self.navigationController popViewControllerAnimated:YES];
    }];
    
    self.rightBarItem = [[SCBarButtonItem alloc] initWithTitle:NSLocalizedString(@"jrd_save", nil) style:SCBarButtonItemStylePlain handler:^(id sender) {
        NSString* password = [JrdDatamanager manager].user.password;
        NSDictionary *parameter_ = @{
                                     @"userid":[JrdDatamanager manager].user.userId,//@(3),//[result valueForKey:@"id"]
                                     @"phone":[JrdDatamanager manager].user.phoneNumber,
                                     @"email":[JrdDatamanager manager].user.userEamil,
                                     @"password":[JrdDatamanager manager].user.password};
        [CKHttpCommunicate createRequest:HTTP_UPDATE_USER_INFO WithParam:parameter_ withMethod:GET success:^(id result) {
            if(result){
                NSLog(@"update success");
                if(true == is_need_uploadImage){
                    //upload image
                    is_need_uploadImage = false;
                    /*UIImage *image=[UIImage imageWithContentsOfFile:self.imagePath];
                    UIImage *new_image = [self imageCompressForWidth:image targetWidth:image.size.width/4];
                    NSData* imageData = UIImageJPEGRepresentation(new_image,0.5);//UIImagePNGRepresentation(image);
                    NSDictionary *parameter_1 = @{
                                                 @"userid":[JrdDatamanager manager].user.userId,
                                                 @"imagefile":imageData};

                    [CKHttpCommunicate createRequest:HTTP_UPLOAD_IMAGE WithParam:parameter_1 withMethod:POST success:^(id result) {
                        if(result){
                        }
                    }failure:^(NSError *erro) {
                        NSLog(@"zlwu add ");
                    } showHUD:self.view];*/

                }
            }
        }failure:^(NSError *erro) {
            NSLog(@"zlwu add ");

        } showHUD:self.view];

        NSLog(@"save the change of account");
        [self.navigationController popViewControllerAnimated:YES];

    }];

}


-(UIImage *) imageCompressForWidth:(UIImage *)sourceImage targetWidth:(CGFloat)defineWidth//图片压缩，第二个参数为最终宽度

{
    
    CGSize imageSize = sourceImage.size;
    
    CGFloat width = imageSize.width;
    
    CGFloat height = imageSize.height;
    
    CGFloat targetWidth = defineWidth;
    
    CGFloat targetHeight = (targetWidth / width) * height;
    
    UIGraphicsBeginImageContext(CGSizeMake(targetWidth, targetHeight));
    
    [sourceImage drawInRect:CGRectMake(0,0,targetWidth,  targetHeight)];
    
    UIImage* newImage =UIGraphicsGetImageFromCurrentImageContext();
    
    UIGraphicsEndImageContext();
    
    return newImage;
    
}
- (void)configureTableView {
    
    self.tableView                 = [[UITableView alloc] initWithFrame:CGRectMake(0, NAVIGATION_BAR_HEIGHT, SCREEN_WIDTH, SCREEN_HEIGHT - (NAVIGATION_BAR_HEIGHT))];
    self.tableView.separatorStyle  = UITableViewCellSeparatorStyleNone;
    self.tableView.delegate        = self;
    self.tableView.dataSource      = self;
    self.tableView.backgroundColor = JrdTableHeadColor;
    [self.view addSubview:self.tableView];
    
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

#pragma mark - TableView
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return JRD_CHANGE_SECTION;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if(0 == indexPath.section){
        return 70;
    }else{
        return 50;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *CellIdentifier = @"Cell";
    
    JrdChangeAccountCellTableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];//[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[JrdChangeAccountCellTableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier];
    }
    if(0 == indexPath.section){
        UIView *headerLineView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 0.5)];
        headerLineView.backgroundColor = JrdSpeLineColorExt;
        [cell addSubview:headerLineView];
        
        UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(0, (70 - 0.5), SCREEN_WIDTH, 0.5)];
        lineView.backgroundColor = JrdSpeLineColorExt;
        [cell addSubview:lineView];

    }else{
        UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(0, (50 - 0.5), SCREEN_WIDTH, 0.5)];
        lineView.backgroundColor = JrdSpeLineColorExt;
        [cell addSubview:lineView];

    }
    

    UIFont *myFont = [UIFont fontWithName:@"HelveticaNeue-Light" size:17.0];
    cell.textLabel.font = myFont;
    [cell.textLabel setTextColor:[UIColor JRDColorMainSettingCellText]];
    cell.detailTextLabel.font = myFont;
    cell.detailTextLabel.textColor = [UIColor JRDColorStandardBlue];
        switch (indexPath.section) {
            case  JRD_CHANGE_PHOTO:{
                UIImage *image=[UIImage imageWithContentsOfFile:self.imagePath];
                [cell initViews:70];
                cell.titleLabel.text = NSLocalizedString(@"jrd_change_photo", nil);//@"Change Photo";
                cell.icon.contentMode = UIViewContentModeScaleAspectFill;
                cell.icon.clipsToBounds = YES;
                cell.icon.layer.cornerRadius = cell.icon.bounds.size.width/2; //kAvatarHeight / 2.0;
                cell.icon.layer.borderColor = RGB(0x8a8a8a, 1.0).CGColor;
                cell.icon.layer.borderWidth = 1.0f;
                cell.icon.tag = 100;
                //根据图片路径载入图片
                if (image == nil) {
                    
                    cell.icon.image = [UIImage imageNamed:@"ico_username"];
                }else {
                    //显示保存过的
                    cell.icon.image  = image;
                }

                
            }
                break;
            case  JRD_CHANGE_PWD:
            {
                [cell initViews:50];
                cell.titleLabel.text = NSLocalizedString(@"jrd_change_pwd", nil);//@"Change Photo";
            }
                break;
            case  JRD_CHANGE_EMAIL:
            {
                [cell initViews:50];
                
                cell.titleLabel.text = NSLocalizedString(@"jrd_change_email", nil);
                cell.valueLabel.text = [JrdDatamanager manager].user.userEamil;
            }
                break;
            case  JRD_CHANGE_PHONE:
            {
                [cell initViews:50];

                cell.titleLabel.text = NSLocalizedString(@"jrd_change_Phone", nil);//@"Change Photo";
                cell.valueLabel.text = [JrdDatamanager manager].user.phoneNumber;//@"123456789";
            }
                break;
            case JRD_LOGOUT:
            {
                [cell initViews:50];

                cell.titleLabel.text = NSLocalizedString(@"jrd_Logout", nil);//@"Change Photo";
            }
                break;
        }
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    switch (indexPath.section) {
        case  JRD_CHANGE_PHOTO:{
            [self changeImage];
        }break;
        case JRD_LOGOUT:{
            UIAlertView* alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"jrd_Logout", nil) message:NSLocalizedString(@"jrd_Logout_confirm", nil) delegate:self cancelButtonTitle:NSLocalizedString(@"jrd_cancel", nil) otherButtonTitles:NSLocalizedString(@"jrd_OK", nil), nil];
            [alert show];

        }
        break;
        case JRD_CHANGE_PWD:{
            JrdChangePasswordViewController* vc = [[JrdChangePasswordViewController alloc] init];
            [self.navigationController pushViewController:vc animated:YES];
        }break;
        case JRD_CHANGE_EMAIL:{
            JrdChangeEmailViewController* vc = [[JrdChangeEmailViewController alloc] init];
            [self.navigationController pushViewController:vc animated:YES];

        }break;
        case JRD_CHANGE_PHONE:{
            JrdChangePhoneViewController* vc = [[JrdChangePhoneViewController alloc] init];
            [self.navigationController pushViewController:vc animated:YES];
            
        }break;
        default:
            break;
    }
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    NSLog(@"zlwu buttonIndex = %ld", (long)buttonIndex);
    if(1 == buttonIndex){
        //delete image path
        NSArray *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *documentPath = [path objectAtIndex:0];
        
        NSString *imageDocPath = [documentPath stringByAppendingPathComponent:@"ImageFile"];
        //创建ImageFile文件夹
        [[NSFileManager defaultManager] createDirectoryAtPath:imageDocPath withIntermediateDirectories:YES attributes:nil error:nil];
        
        NSString* imagePath = [imageDocPath stringByAppendingPathComponent:@"image.png"];

        NSFileManager * fileManager = [[NSFileManager alloc]init];
        [fileManager removeItemAtPath:imagePath error:nil];

        JrdLoginViewController* loginViewController = [[JrdLoginViewController alloc] init];
        loginViewController.isNeedBack = NO;
        //[self.navigationController pushViewController:<#(nonnull UIViewController *)#> animated:<#(BOOL)#>];
        [[NSUserDefaults standardUserDefaults]setBool:NO forKey:@"isLogin"];
        [JrdDatamanager manager].user = nil;
        [self presentViewController:loginViewController animated:YES completion:nil];
            
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if(JRD_CHANGE_PHOTO == section){
        return 15;
    }else{
        return 10;

    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView* headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, tableView.size.width, 10)];
    headerView.backgroundColor = JrdTableHeadColor;//[UIColor clearColor];
    return headerView;
}

- (nullable UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section;   // custom view for footer. will be adjusted to default or specified footer height
{
    UIView* footView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, tableView.size.width, 5)];
    if(JRD_LOGOUT == section){
        footView.backgroundColor = [UIColor clearColor];//[UIColor clearColor];
    }else{
        footView.backgroundColor = JrdTableHeadColor;//[UIColor clearColor];
    }
    return footView;
    
}


//Pick Picture
- (void)changeImage{
    NSLog(@"tap to change image");
    UIActionSheet *myActionSheet = [[UIActionSheet alloc]
                                    initWithTitle:nil
                                    delegate:self
                                    cancelButtonTitle:@"取消"
                                    destructiveButtonTitle:nil
                                    otherButtonTitles: @"从相册选择", @"拍照",nil];
    [myActionSheet showInView:self.view];
}

-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
    switch (buttonIndex) {
        case 0:
            //从相册选择
            [self LocalPhoto];
            break;
        case 1:
            //拍照
            [self takePhoto];
            break;
        default:
            break;
    }
}

//从相册选择
-(void)LocalPhoto{
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    //资源类型为图片库
    picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    picker.delegate = self;
    //设置选择后的图片可被编辑
    picker.allowsEditing = YES;
    //[self.navigationController pushViewController:picker animated:YES];
    //[self presentModalViewController:picker animated:YES];
    //[self.view addSubview:picker.view];
    [self presentViewController:picker animated:YES completion:^{
        picker.delegate = self;
    }];
}

//拍照
-(void)takePhoto{
    //资源类型为照相机
    UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
    //判断是否有相机
    if ([UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera]){
        UIImagePickerController *picker = [[UIImagePickerController alloc] init];
        picker.sourceType = sourceType;
        //设置拍照后的图片可被编辑
        picker.allowsEditing = YES;
        //资源类型为照相机
        [self presentViewController:picker animated:YES completion:^{
            picker.delegate = self;
        }];
    }
}

//图像选取器的委托方法，选完图片后回调该方法
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(NSDictionary *)editingInfo{
    
    //当图片不为空时显示图片并保存图片
    if (image != nil) {
        [self.tableView reloadData];
        
    }
    //关闭相册界面
    [picker popViewControllerAnimated:YES];
    is_need_uploadImage = true;
}

- (UIImage *)scaleImage:(UIImage *)image toScale:(float)scaleSize
{
    UIGraphicsBeginImageContext(CGSizeMake(image.size.width*scaleSize,image.size.height*scaleSize));
    [image drawInRect:CGRectMake(0, 0, image.size.width * scaleSize, image.size.height *scaleSize)];
    UIImage *scaledImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    NSLog(@"%@",NSStringFromCGSize(scaledImage.size));
    return scaledImage;
}


- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    is_need_uploadImage = true;
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        
        if (info != nil) {
            UIImage* original_image = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
            original_image = [self scaleImage:original_image toScale:0.3];
            NSData *data;
            //判断图片是不是png格式的文件
            if (UIImagePNGRepresentation(original_image)) {
                //返回为png图像。
                data = UIImagePNGRepresentation(original_image);
            }else {
                //返回为JPEG图像。
                data = UIImageJPEGRepresentation(original_image, 1.0);
            }
            //保存
            [[NSFileManager defaultManager] createFileAtPath:self.imagePath contents:data attributes:nil];
            //[self.tableView reloadData];
        }
        [[NSNotificationCenter defaultCenter] postNotificationName:kPickImageNotification object:self];
    });
    
    //upload image to web
     UIImage *image=[UIImage imageWithContentsOfFile:self.imagePath];
     //UIImage *new_image = [self imageCompressForWidth:image targetWidth:image.size.width/4];
     NSData* imageData = UIImageJPEGRepresentation(image,0.5);//UIImagePNGRepresentation(image);
     NSDictionary *parameter_1 = @{
     @"userid":[JrdDatamanager manager].user.userId
     };
    //@"icon_url":imageData
     NSDictionary *parameter_2 = @{
                                  @"icon_url":imageData//[JrdDatamanager manager].user.userId
                                  };
    [CKHttpCommunicate createRequest:HTTP_UPLOAD_IMAGE WithParam:nil withExParam:parameter_2 withMethod:POST success:^(id result){
        NSLog(@"zlwu add for success");
    } uploadFileProgress:^(NSProgress *uploadProgress) {
        NSLog(@"zlwu add for upload");

    } failure:^(NSError *erro) {
        NSLog(@"zlwu add for failure");
    } ];
    

     /*[CKHttpCommunicate createRequest:HTTP_UPLOAD_IMAGE WithParam:parameter_1 withMethod:POST success:^(id result) {
     if(result){
     }
     }failure:^(NSError *erro) {
     NSLog(@"zlwu add ");
     } showHUD:self.view];*/

    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)loadImageAndSave:(id)result{
    NSData* image_data = (NSData*)result;
    UIImage* image = [UIImage imageWithData:image_data];
    
    NSArray *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentPath = [path objectAtIndex:0];
    
    NSString *imageDocPath = [documentPath stringByAppendingPathComponent:@"ImageFile"];
    //创建ImageFile文件夹
    [[NSFileManager defaultManager] createDirectoryAtPath:imageDocPath withIntermediateDirectories:YES attributes:nil error:nil];
    
    NSString* imagePath = [imageDocPath stringByAppendingPathComponent:@"image.png"];
    NSData *data;
    
    if (UIImagePNGRepresentation(image)) {
        //返回为png图像。
        data = UIImagePNGRepresentation(image);
    }else {
        //返回为JPEG图像。
        data = UIImageJPEGRepresentation(image, 1.0);
    }
    [[NSFileManager defaultManager] createFileAtPath:imagePath contents:data attributes:nil];
    
}
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    NSLog(@"cancel to pick controller");
    [self dismissViewControllerAnimated:YES completion:nil];
}

@end
